<?php
header('content-type: text/html;charset=utf-8;');
function shop()
{
    $uname = $_POST['username'];
    $title = $_POST['title'];
    $price = $_POST['price'];
    $img = $_POST['img'];

    $link = mysqli_connect('127.0.0.1', 'root', 'root', 'demo1');

    //查找有没有相同的数据已经在数据库了
    $sql = "SELECT * FROM `shop` WHERE `username`='$uname' AND `title`='$title' ";

    $res = mysqli_query($link, $sql);

    $data = mysqli_fetch_all($res, MYSQLI_ASSOC); 

    // 你第一次添加的时候
    // 这个 $data 应该是没有， 那么你的 $data 就是一个空数组， 你拿到 0 修改里面的 num 属性不就报错了吗

    // $num = $data[0]['num'] + 1;
    // print_r($data[0]['num']);
    if($data) {
        $num = $data[0]['num'] + 1;
        //有的话把数量加一
        $res1 = mysqli_query($link, "UPDATE `shop` SET `num`='$num' WHERE `username`='$uname' AND `title`='$title'");
        mysqli_close($link);
        if ($res1) {
            $arr = array("message" => "添加成功",
            "code" => 1,
            "username" => $uname,
            "title" => $title,
            "price" => $price,
            "img" => $img
            );
        } else {
            $arr = array("message" => "添加失败", "code" => 0);
        }
        
        // 把这关联型数组返回
        print_r(json_encode($arr));
    }else {
        //没有则创建一条
        $query = mysqli_query($link, "INSERT INTO `shop` (`username`, `title`, `price_info`, `img`, `num`) VALUES('$uname', '$title', '$price', '$img', 1)");
        
        mysqli_close($link);
        if ($query) {
            $arr = array("message" => "添加成功",
            "code" => 1,
            "username" => $uname,
            "title" => $title,
            "price" => $price,
            "img" => $img
            );
        } else {
            $arr = array("message" => "添加失败", "code" => 0);
        }
        
        // 把这关联型数组返回
        print_r(json_encode($arr));
    }
    
    
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    shop();
}